package com.example.service.serviceImpl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.common.UserHolder;
import com.example.domain.entity.*;
import com.example.domain.vo.OrdersVo;
import com.example.mapper.NoticeMapper;
import com.example.mapper.OrdersMapper;
import com.example.mapper.RoomMapper;
import com.example.mapper.UserMapper;
import com.example.service.OrderService;
import com.example.service.ReserveService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OrderServiceAImpl implements OrderService {

    @Autowired
    private OrdersMapper orderMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private ReserveService reserveService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    @Transactional
    public Result addOrders(OrdersVo vo) {

        if (vo.getStartTime().isAfter(vo.getEndTime())) {
            return Result.error("开始时间不能大于结束时间");
        }

        if (vo.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.error("结束时间不能小于当前时间");
        }

        User user = userMapper.selectById(vo.getUserId());
        Notice notice = new Notice();
        notice.setUserId(vo.getUserId());
        notice.setName(user.getUsername());
        notice.setDescription("预约" + vo.getRoomName() + "会议室成功");
        notice.setTime(DateUtil.now());
        noticeMapper.insert(notice);



        long orderId = IdWorker.getId();
        vo.setOrderId(orderId);
        vo.setCreateTime(LocalDateTime.now());
        vo.setPaymentDeadline(LocalDateTime.now().plusMinutes(30));
        Orders orders = new Orders();
        BeanUtils.copyProperties(vo, orders);

        //todo
//        Room room = new Room();
//        room.setId(vo.getRoomId());
//        room.setStatus(1);
//        roomMapper.updateById(room);

        orderMapper.insert(orders);

        return Result.success(vo);
    }

    @Override
    @Transactional
    public Result pay(Orders orders) {

        if (orders == null ){
            return Result.error("订单不存在");
        }
        if(orders.getPaymentDeadline().isBefore(LocalDateTime.now())){
            return Result.error("订单已过期");
        }
        if(orders.getStatus() == 2){
            return Result.error("订单已支付");
        }
        if (orders.getStatus() == 4){
            return Result.error("订单已过期");
        }

        Orders tmp = new Orders();
        tmp.setOrderId(orders.getOrderId());
        tmp.setStatus(2);
        tmp.setActualPaymentTime(LocalDateTime.now());
        orderMapper.updateById(tmp);

        //todo
//        Room room = new Room();
//        room.setId(orders.getRoomId());
//        room.setStatus(2);
//        roomMapper.updateById(room);
        return Result.success();
    }

    @Override
    public Page<OrdersVo> findBySearch(Params params) {
        // 创建 MyBatis-Plus 的分页对象
        Page<Orders> page = new Page<>(params.getPageNum(), params.getPageSize());
        Account user = UserHolder.getUser();
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        // 根据 params 构建查询条件
        if (params != null) {
            if (params.getName() != null && !params.getName().isEmpty()) {
                queryWrapper.like("name", params.getName());
            }
            queryWrapper.eq(user.getRole().equals("USER"),"user_id",user.getId() );
        }

        // 按 id 倒序排序
        queryWrapper.orderByDesc("order_id");
        Page<Orders> ordersPage = orderMapper.selectPage(page, queryWrapper);
        List<Orders> ordersList = ordersPage.getRecords();
        if (ordersList == null || ordersList.isEmpty()){
            return null;
        }

        List<Integer> userIds = ordersList.stream().map(Orders::getUserId).collect(Collectors.toList());
        Map<Integer, String> userInfoMap = userMapper.selectBatchIds(userIds).stream().collect(Collectors.toMap(User::getId, User::getUsername));
        List<Integer> roomIds = ordersList.stream().map(Orders::getRoomId).collect(Collectors.toList());
        Map<Integer, String> roomInfoMap = roomMapper.selectBatchIds(roomIds).stream().collect(Collectors.toMap(Room::getId, Room::getName));


        List<OrdersVo> voList = new ArrayList<>();
        ordersList.forEach(orders -> {
            OrdersVo vo = new OrdersVo();
            BeanUtils.copyProperties(orders, vo);
            String userName = userInfoMap.get(orders.getUserId());
            if (userName != null){
                vo.setUserName(userName);
            }
            String roomName = roomInfoMap.get(orders.getRoomId());
            if (roomName != null){
                vo.setRoomName(roomName);
                vo.setName(roomName);
            }
            voList.add(vo);
        });
        Page<OrdersVo> ordersVoPage = new Page<>(params.getPageNum(), params.getPageSize());
        BeanUtils.copyProperties(ordersPage, ordersVoPage);
        ordersVoPage.setRecords(voList);
        return ordersVoPage;
    }

    @Override
    public void confirm(Orders orders) {
        //订单置为已取消状态
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getOrderId,orders.getOrderId())
//                .eq(Orders::getStatus,6)
                .set(Orders::getStatus,3);
        orderMapper.update(null,updateWrapper);
        //会议室置为空闲状态
        LambdaUpdateWrapper<Room> roomLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        roomLambdaUpdateWrapper.eq(Room::getId,orders.getRoomId())
                               .set(Room::getStatus,0);
        roomMapper.update(null,roomLambdaUpdateWrapper);
    }

    @Override
    public void cancel(Orders orders) {
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getOrderId,orders.getOrderId())
//                .eq(Orders::getStatus,2)
                .set(Orders::getStatus,5);
        orderMapper.update(null,updateWrapper);
//        reserve.setReserveStatus(1);
//        reserve.setUseStatus(3);
//        reserveMapper.updateById(reserve);
//        roomMapper.updateByIdToKong(reserve.getRoomId());
    }

    @Override
    public void pass(Orders orders) {
        //获取对应的用户信息
        Integer userId = orders.getUserId();
        User user = userMapper.selectById(userId);
        //获取对用的会议室信息
        Integer roomId = orders.getRoomId();
        Room room = roomMapper.selectById(roomId);
        //插入记录
        Notice notice = new Notice();
        notice.setName(user.getName());
//        notice.setDescription("预约" + reserve.getName() + "自习室成功，请留意预约时间进行使用");
        notice.setName(user.getName());
        notice.setDescription("取消预约" + room.getName() + "自习室成功");
        notice.setTime(DateUtil.now());
        notice.setUserId(user.getId());
        noticeMapper.insert(notice);

//        reserve.setReserveStatus(1);
//        reserve.setUseStatus(1);
//        reserveMapper.updateById(reserve);
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getOrderId,orders.getOrderId())
//                .eq(Orders::getStatus,5)
                .set(Orders::getStatus,6);
        orderMapper.update(null,updateWrapper);
    }
}